package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.JSONUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.StringUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyListView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Request;

/**
 * 产检提醒历史
 * Created by gaoge on 2017/9/14.
 */

public class RemindHistoryActivity extends BaseActivity implements MyListView.IXListViewListener {

    //标题
    private TextView title = null;
    //返回键
    private ImageView img_back = null;
    //数据显示列表
    private MyListView listview = null;
    //点击项
    private int click = -1;
    //记录上次点击项
    private int oldClick = -1;
    //适配器
    private MyAdapter myAdapter = null;
    //加载框
    AlertDialog dialog;
    //保存数据集合
    private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    //旋转动画
    Animation rotate;
    //关闭旋转动画
    Animation closeRotate;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 10;
    //数据总量
    private int totalCount = 0;
    //数据库对象
    private DBManager db = null;
    //无数据页面
    private LinearLayout no_data_linearlayout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载布局
        setContentView(R.layout.remind_history_activity);
        //初始化组件
        init();
    }

    /**
     * 初始化组件
     */
    private void init() {
        //初始化数据库对象
        db = new DBManager(this);
        //初始化组件
        title = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        listview = (MyListView) findViewById(R.id.listview);
        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        //设置标题
        title.setText("提醒历史");
        //设置返回键事件
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //状态列表添加单击事件
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (click == -1) {
                    click = position;
                    oldClick = -1;
                } else {
                    oldClick = click;
                    if (click == position) {
                        click = -1;
                    } else {
                        click = position;
                    }
                }
                myAdapter.notifyDataSetInvalidated();
            }
        });
        // 加载动画
        rotate = AnimationUtils.loadAnimation(RemindHistoryActivity.this, R.anim.widget_rotate);
        closeRotate = AnimationUtils.loadAnimation(RemindHistoryActivity.this, R.anim.close_rotate);
        // 动画执行完后停留在执行完的状态
        rotate.setFillAfter(true);
        closeRotate.setFillAfter(true);
        //添加适配器
        myAdapter = new MyAdapter(RemindHistoryActivity.this, list);
        listview.setAdapter(myAdapter);
        //实现
        realize();
    }

    /**
     * 功能实现
     */
    private void realize() {
        //获取列表数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            dialog = new MyAlertDialog().ShowDialog(RemindHistoryActivity.this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            getListData();
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }

    }

    /**
     * 下载列表数据
     */
    public void getListData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.getRemindHistory(currentPage, number)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = null;
                    response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    int code = response.code();
                    Log.e("bodys",bodys);
                    if (code == 204 || code == 200) {
                        if (!bodys.equals("")) {
                            JSONObject jsonObject = new JSONObject(bodys);
                            //获取数据总量
                            if (totalCount == 0) {
                                totalCount = Integer.parseInt(jsonObject.get("totalCount").toString());
                                list = new ArrayList<HashMap<String, String>>();
                            }
                            list.addAll(JSONUtil.jsonAryToListMap(jsonObject
                                    .getJSONArray("items")));
                            loginHandler.sendEmptyMessage(1);
                        } else {
                            loginHandler.sendEmptyMessage(2);
                        }
                    } else {
                        loginHandler.sendEmptyMessage(2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    loginHandler.sendEmptyMessage(2);
                }
            }
        }).start();
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            onLoad();
            switch (msg.what) {
                case 1:
                    if (listview.getVisibility() == View.GONE) {
                        listview.setVisibility(View.VISIBLE);
                    }
                    listview.setPullLoadEnable(true);
                    listview.setXListViewListener(RemindHistoryActivity.this, totalCount, currentPage, number);
                    myAdapter.getData(list);
                    break;
                case 2:
                    if (no_data_linearlayout.getVisibility() == View.GONE) {
                        no_data_linearlayout.setVisibility(View.VISIBLE);
                    }
                    if (listview.getVisibility() == View.VISIBLE) {
                        listview.setVisibility(View.GONE);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 状态列表适配器
     */
    class MyAdapter extends BaseAdapter {
        LayoutInflater lf = null;
        ArrayList<HashMap<String, String>> getData = new ArrayList<HashMap<String, String>>();
        ViewHolder viewHolder = null;

        public MyAdapter(Context context,
                         ArrayList<HashMap<String, String>> getData) {
            lf = LayoutInflater.from(context);
            this.getData = getData;
        }

        @Override
        public int getCount() {
            return getData.size();
        }

        public void getData(ArrayList<HashMap<String, String>> data) {
            this.getData = data;
            notifyDataSetChanged();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = lf.inflate(R.layout.remind_history_item, null);
                viewHolder.textView = (TextView) convertView.findViewById(R.id.textview);
                viewHolder.content = (TextView) convertView.findViewById(R.id.content);
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageview);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.textView.setText(getData.get(position).get("antenatalCareTime").split("T")[0]);
            if (StringUtil.judgeNull(getData.get(position).get("remark"))) {
                viewHolder.content.setText(getData.get(position).get("remark"));
            } else {
                viewHolder.content.setText("未设置产检提醒备注");
            }

            //按钮控制
            if (click == position) {
                viewHolder.content.setVisibility(View.VISIBLE);
                // 执行动画
                viewHolder.imageView.startAnimation(rotate);
            } else {
                if (oldClick == position) {
                    // 执行动画
                    viewHolder.imageView.startAnimation(closeRotate);
                } else {
                    viewHolder.imageView.clearAnimation();
                    viewHolder.imageView.setImageResource(R.mipmap.jiantou);
                }
                viewHolder.content.setVisibility(View.GONE);
            }
            return convertView;
        }

        /**
         * 包装类
         */
        class ViewHolder {
            private TextView textView = null;
            private TextView content = null;
            private ImageView imageView = null;
        }
    }

    //上拉加载更多
    @Override
    public void onLoadMore() {
        if (totalCount > currentPage * number) {
            currentPage = currentPage + 1;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(AppConstant.THREAD_SLEEP);
                        getListData();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            onLoad();
        }
    }

    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        listview.stopLoadMore();
    }
}
